//
//  UserDataBaseTool.m
//  AAIM
//
//  Created by awh on 2019/12/28.
//  Copyright © 2019年 AAIM. All rights reserved.
//

#import "UserDataBaseTool.h"
#import "ContactRequestLogic.h"
@interface UserDataBaseTool ()

@property(nonatomic, copy) NSString *friendTableName;
@property(nonatomic, copy) NSString *groupTableName;
@property(nonatomic, strong) FMDatabaseQueue *friennDBQueue;
@property(nonatomic, strong) FMDatabaseQueue *groudDBQueue;
@property(nonatomic,strong) FMDatabaseQueue *publicDBQueue;
@property(nonatomic, copy) NSString *publicTableName;

@end

@implementation UserDataBaseTool

static UserDataBaseTool *single = nil;

+ (instancetype)shareUserDataBaseTool {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        single = [[self alloc] init];
    });
    return single;
}
- (instancetype)init {
    if (self = [super init]) {
        [self initDataBase];
    }
    return self;
}

- (void)initDataBase {
    NSString *dbPath  =[CacheTool readUserDefaults:@"APPDATABASE_KEY"];
    // 2.创建对应路径下数据库
    self.friennDBQueue = [[FMDatabaseQueue alloc] initWithPath:dbPath];
    self.groudDBQueue  = [[FMDatabaseQueue alloc] initWithPath:dbPath];
    self.publicDBQueue = [[FMDatabaseQueue alloc]initWithPath:dbPath];
}

- (void)createTable {
    [self.friennDBQueue inDatabase:^(FMDatabase *db) {
        NSString *createTableSql = [NSString stringWithFormat:@"create table if not exists %@ ('fuuid' TEXT, 'head' TEXT, 'nickname' TEXT )", self.friendTableName];
        [db executeUpdate:createTableSql];
    }];
    
    [self.groudDBQueue inDatabase:^(FMDatabase *db) {
        NSString *createTableSql = [NSString stringWithFormat:@"create table if not exists %@ ('user_id' TEXT, 'groupHead' TEXT, 'groupName' TEXT , 'isMeCreate' INTEGER)", self.groupTableName];
        [db executeUpdate:createTableSql];
    }];
    [self.publicDBQueue inDatabase:^(FMDatabase * _Nonnull db) {
        NSString *createTableSql = [NSString stringWithFormat:@"create table if not exists %@ ('head' TEXT, 'udid' TEXT, 'describe' TEXT, 'title' TEXT )", self.publicTableName];
               [db executeUpdate:createTableSql];
    }];
    
}

-(void)savePublicModel:(PublicModel *)model type:(NSInteger)type{
    if (type == 3) {
        [self insertPublics:model];
    }
}

- (void)saveContactModel:(ContactModel *)model type:(NSInteger)type
{
    if (type==1) {
        [self insertFriends:model];
    }else
    {
        [self insertGroups:model];
    }
}

-(void)insertPublics:(PublicModel*)fModel
{
    [self.publicDBQueue inDatabase:^(FMDatabase * _Nonnull db) {
        NSString *tableNameHead = [NSString stringWithFormat:@"insert into '%@' ", self.publicTableName];
        NSString *content = [NSString stringWithFormat:@"(udid, head, title, describe ) values (?, ?, ?, ?)"];
        NSString *sql = [NSString stringWithFormat:@"%@%@", tableNameHead, content];
        [db executeUpdate:sql,fModel.udid,fModel.head,fModel.title,fModel.describe];
    }];
}

-(void)insertFriends:(ContactModel*)fModel
{
    [self.friennDBQueue inDatabase:^(FMDatabase * _Nonnull db) {
        NSString *tableNameHead = [NSString stringWithFormat:@"insert into '%@' ", self.friendTableName];
        NSString *content = [NSString stringWithFormat:@"(fuuid, head, nickname ) values (?, ?, ?)"];
        NSString *sql = [NSString stringWithFormat:@"%@%@", tableNameHead, content];
        [db executeUpdate:sql,fModel.fuuid,fModel.head,fModel.nickname];
    }];
}
-(void)insertGroups:(ContactModel*)gModel
{
    //user_id  群id；
    [self.groudDBQueue inDatabase:^(FMDatabase * _Nonnull db) {
        NSString *tableNameHead = [NSString stringWithFormat:@"insert into '%@' ", self.groupTableName];
        NSString *content = [NSString stringWithFormat:@"(user_id, groupHead, groupName, isMeCreate) values (?, ?, ? ,?)"];
        NSString *sql = [NSString stringWithFormat:@"%@%@", tableNameHead, content];
        [db executeUpdate:sql,gModel.user_id,gModel.groupHead,gModel.groupName,@(gModel.isMeCreate)];
    }];
    
}

-(void)SavePublicDataSuccess:(void (^)(BOOL))Success{
    [self deleteFriendWithGroupDataWithType:3];
    //关注后保存
    
}

- (void)SaveFriendsWithGroupsDataSuccess:(void(^)(BOOL isOK))Success
{
       [self deleteFriendWithGroupDataWithType:1];
       [self deleteFriendWithGroupDataWithType:2];
       [ContactRequestLogic requestFriendListWithPage:@"1" Success:^(NSDictionary * _Nonnull Dict) {
            AAIMLog(@"好友信息：%@",Dict);
            NSArray * dataArray= Dict[@"data"];
            if (dataArray.count>0) {
                for (NSDictionary * dic in dataArray) {
                    ContactModel * model = [ContactModel mj_objectWithKeyValues:dic];
                    [self insertFriends:model];
                }
            }
           //群
           [ContactRequestLogic requestGetGroupsListSuccess:^(NSDictionary * _Nonnull Dict) {
               NSDictionary * dataDic =Dict[@"data"];
               AAIMLog(@"群信息：%@",Dict);
               NSArray* createGroupsArray=dataDic[@"createGroups"];
               if (createGroupsArray.count>0) {
                   for (NSDictionary * dic in createGroupsArray) {
                       ContactModel * model = [ContactModel mj_objectWithKeyValues:dic];
                       model.isMeCreate=1;
                       [self insertGroups:model];
                   }
               }
               NSArray* joinGroupsArray=dataDic[@"joinGroups"];
               if (joinGroupsArray.count>0) {
                   for (NSDictionary * dic in joinGroupsArray) {
                       ContactModel * model = [ContactModel mj_objectWithKeyValues:dic];
                       model.isMeCreate=2;
                       [self insertGroups:model];
                   }
               }
               Success(YES);
           } failure:^(NSString * _Nonnull errMsg) {
               Success(YES);
           }];
        } failure:^(NSString * _Nonnull errMsg) {
            Success(YES);
        }];
}
-(void)reloadData:(NSInteger)type Success:(void(^)(BOOL isOK))Success
{
    [self deleteFriendWithGroupDataWithType:type];
    if (type==1) {
        [ContactRequestLogic requestFriendListWithPage:@"1" Success:^(NSDictionary * _Nonnull Dict) {
            AAIMLog(@"好友信息：%@",Dict);
            NSArray * dataArray= Dict[@"data"];
            if (dataArray.count>0) {
                for (NSDictionary * dic in dataArray) {
                    ContactModel * model = [ContactModel mj_objectWithKeyValues:dic];
                    [self insertFriends:model];
                }
            }
            Success(YES);
        } failure:^(NSString * _Nonnull errMsg) {
            Success(NO);
        }];
        
    }else if (type == 3){
        //公众号，重新请求后台数据
        
    } else
    {
        //群
        [ContactRequestLogic requestGetGroupsListSuccess:^(NSDictionary * _Nonnull Dict) {
            NSDictionary * dataDic =Dict[@"data"];
            AAIMLog(@"群信息：%@",Dict);
            NSArray* createGroupsArray=dataDic[@"createGroups"];
            if (createGroupsArray.count>0) {
                for (NSDictionary * dic in createGroupsArray) {
                    ContactModel * model = [ContactModel mj_objectWithKeyValues:dic];
                    model.isMeCreate=1;
                    [self insertGroups:model];
                }
            }
            NSArray* joinGroupsArray=dataDic[@"joinGroups"];
            if (joinGroupsArray.count>0) {
                for (NSDictionary * dic in joinGroupsArray) {
                    ContactModel * model = [ContactModel mj_objectWithKeyValues:dic];
                    model.isMeCreate=2;
                    [self insertGroups:model];
                }
            }
            Success(YES);
        } failure:^(NSString * _Nonnull errMsg) {
            Success(NO);
        }];
    }
}

- (NSArray<PublicModel *> *)queryAllPublic{
    NSMutableArray *conversations = [NSMutableArray new];
       [self.publicDBQueue inDatabase:^(FMDatabase *db) {
           // 获取全部会话信息
           NSString *sql = [NSString stringWithFormat:@"select * from %@ ;", self.publicTableName];
           FMResultSet *result = [db executeQuery:sql];
           while ([result next]) {
               [conversations addObject:[self dataWithPublic:result]];
           }
       }];
       return conversations;
}


- (NSArray<ContactModel *> *)queryAllFriends
{
    NSMutableArray *conversations = [NSMutableArray new];
    [self.friennDBQueue inDatabase:^(FMDatabase *db) {
        // 获取全部会话信息
        NSString *sql = [NSString stringWithFormat:@"select * from %@ ;", self.friendTableName];
        FMResultSet *result = [db executeQuery:sql];
        while ([result next]) {
            [conversations addObject:[self dataWith:result]];
        }
    }];
    return conversations;
}
- (NSArray<ContactModel *> *)queryAllGroups
{
    NSMutableArray *conversations = [NSMutableArray new];
    [self.groudDBQueue inDatabase:^(FMDatabase *db) {
        // 获取全部会话信息
        NSString *sql = [NSString stringWithFormat:@"select * from %@ ;", self.groupTableName];
        FMResultSet *result = [db executeQuery:sql];
        while ([result next]) {
            [conversations addObject:[self dataWith:result]];
        }
    }];
    return conversations;
}
-(BOOL)isGroupMembersWithgId:(NSInteger)gId
{
    NSArray * allGroup=[self queryAllGroups];
    if (allGroup.count>0) {
        for (ContactModel * model  in allGroup) {
            NSLog(@"群id===%@",model.user_id);
            if ([model.user_id integerValue]==gId) {
                return YES;
            }
        }
    }
    return NO;
}
- (ContactModel *)queryFriends:(NSString*)fuuid
{
    NSMutableArray *conversations = [NSMutableArray new];
    [self.friennDBQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"select * from %@ where fuuid = '%@';", self.friendTableName, fuuid];
        FMResultSet *result = [db executeQuery:sql];
        while ([result next]) {
            [conversations addObject:[self dataWith:result]];
        }
    }];
    if (conversations.count > 0) {
        return conversations[0];
    } else {
        return nil;
    }
}
- (ContactModel *)queryGroup:(NSString*)groupid
{
    NSMutableArray *conversations = [NSMutableArray new];
    [self.groudDBQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"select * from %@ where user_id = '%@';", self.groupTableName, groupid];
        FMResultSet *result = [db executeQuery:sql];
        while ([result next]) {
            [conversations addObject:[self dataWith:result]];
        }
    }];
    if (conversations.count > 0) {
        return conversations[0];
    } else {
        return nil;
    }
}

- (PublicModel *)queryPublicUdid:(NSString *)udid
{
    NSMutableArray *conversations = [NSMutableArray new];
    [self.groudDBQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"select * from %@ where udid = '%@';", self.publicTableName, udid];
        FMResultSet *result = [db executeQuery:sql];
        while ([result next]) {
            [conversations addObject:[self dataWithPublic:result]];
        }
    }];
    if (conversations.count > 0) {
        return conversations[0];
    } else {
        return nil;
    }
}

- (void)deleteFriend:(NSString*)fuuid
{
    [self.friennDBQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"delete from %@ where fuuid = '%@'", self.friendTableName, fuuid];
        [db executeUpdate:sql];
    }];
}

- (void)deleteGroup:(NSString*)groupid
{
    [self.groudDBQueue inDatabase:^(FMDatabase *db) {
        NSString *sql = [NSString stringWithFormat:@"delete from %@ where user_id = '%@'", self.groupTableName, groupid];
        [db executeUpdate:sql];
    }];
}

- (void)deletePublicUdid:(NSString *)udid{
    [self.publicDBQueue inDatabase:^(FMDatabase *db) {
           NSString *sql = [NSString stringWithFormat:@"delete from %@ where udid= '%@'", self.publicTableName, udid];
           [db executeUpdate:sql];
       }];
}

-(void)deleteFriendWithGroupDataWithType:(NSInteger)type
{
    if (type==1) {
        [self.friennDBQueue inDatabase:^(FMDatabase *db) {
            NSString *sql = [NSString stringWithFormat:@"delete from %@ ", self.friendTableName];
            [db executeUpdate:sql];
        }];
    }else if (type ==3){
        [self.publicDBQueue inDatabase:^(FMDatabase *db) {
            NSString *sql = [NSString stringWithFormat:@"delete from %@ ", self.publicTableName];
            [db executeUpdate:sql];
        }];
    } else
    {
        [self.groudDBQueue inDatabase:^(FMDatabase *db) {
            NSString *sql = [NSString stringWithFormat:@"delete from %@ ", self.groupTableName];
            BOOL  isdelete =[db executeUpdate:sql];
            if (isdelete) {
                NSLog(@"删除删除删除成功");
            }else
            {
                NSLog(@"删除删除删除成功222222222222");
            }
        }];
    }
}
-(ContactModel*)dataWith:(FMResultSet *)result {
    ContactModel * model =[ContactModel new];
    model.fuuid=[result stringForColumn:@"fuuid"];
    model.head=[result stringForColumn:@"head"];
    model.nickname=[result stringForColumn:@"nickname"];
    
    model.user_id=[result stringForColumn:@"user_id"];
    model.groupHead=[result stringForColumn:@"groupHead"];
    model.groupName=[result stringForColumn:@"groupName"];
    model.isMeCreate=[result intForColumn:@"isMeCreate"];
    return model;
}

-(PublicModel*)dataWithPublic:(FMResultSet *)result {
    PublicModel * model =[PublicModel new];
    model.udid=[result stringForColumn:@"udid"];
    model.head=[result stringForColumn:@"head"];
    model.title=[result stringForColumn:@"title"];
    model.describe=[result stringForColumn:@"describe"];
    return model;
}

#pragma mark - getter

- (NSString *)friendTableName {
    UserModel * model_user= [[LoginManager shareLoginManager] getLoginCustomer];
    return  [NSString stringWithFormat:@"f_friendsData_%@", model_user.fuuid];
}
- (NSString *)groupTableName {
    UserModel * model_user= [[LoginManager shareLoginManager] getLoginCustomer];
    return  [NSString stringWithFormat:@"g_groupsData_%@", model_user.fuuid];
}
- (NSString *)publicTableName {
    UserModel * model_user= [[LoginManager shareLoginManager] getLoginCustomer];
    return  [NSString stringWithFormat:@"p_publicData_%@", model_user.fuuid];
}
@end
